package util

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"reflect"

	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gvalid"
)

func ParseRequest(r *ghttp.Request, params interface{}) {
	if err := r.Parse(params); err != nil {
		if v, ok := err.(gvalid.Error); ok {
			fmt.Println(v.FirstError().Error())
		} else {
			fmt.Println(err.Error())
		}
	}
}
func JsonToStruct(json []byte, object interface{}) error {
	j, err := gjson.DecodeToJson(json)
	if err != nil {
		return err
	}

	if err := j.Scan(object); err != nil {
		return err
	}

	return nil
}
func ParseWhere[R any](req R, where g.Map) {
	value := reflect.ValueOf(req)
	if value.Kind() == reflect.Ptr {
		value = value.Elem()
	}

	for i := 0; i < value.NumField(); i++ {
		field := value.Field(i)
		fieldValue := field.Interface()
		fieldType := field.Type()
		fieldKind := field.Kind()
		fieldName := value.Type().Field(i).Name
		// tagName := field.Tag.Get("json")
		fmt.Println("field:", fieldName, fieldValue, fieldType, fieldKind)

		if fieldName == "Pagination" {
			continue
		}

		switch fieldKind {
		case reflect.Ptr:
			if !field.IsNil() {
				where[fieldName] = field.Elem().Interface()
			}
		case reflect.Struct:
			ParseWhere(fieldValue, where)
		default:
			if !field.IsZero() {
				where[fieldName] = fieldValue
			}
		}
	}
}
